#include "FontManager.h"
#include <spdlog/spdlog.h>
#include <stdexcept>

engine::resource::FontManager::FontManager()
{
    if (!TTF_WasInit())
    {
        if (TTF_Init() == -1)   // 返回 -1 表示失败
        {
            spdlog::error("Failed to initialize SDL_ttf: {}", TTF_GetError());
            throw std::runtime_error("Failed to initialize SDL_ttf");
        }
    }
}

engine::resource::FontManager::~FontManager()
{
    if (!m_fonts.empty())
    {
		spdlog::warn("FontManager 不为空 {}", m_fonts.size());
		clearFonts();
    }
	spdlog::trace("FontManager 析构成功");
	TTF_Quit();
}

TTF_Font* engine::resource::FontManager::loadFont(const std::string& filePath, int fontSize)
{
    if (fontSize <= 0)
    {
		spdlog::error("字体大小无效: {} - {}", filePath, fontSize);   
		return nullptr; 
    }
	FontKey key = std::make_pair(filePath, fontSize);
	auto it = m_fonts.find(key);
    if (it!= m_fonts.end())
    {
		return it->second.get();
    }
	TTF_Font* raw_Font = TTF_OpenFont(filePath.c_str(), fontSize);  
    if (!raw_Font)
    {
		spdlog::error("加载字体失败: {} - {} ", filePath, TTF_GetError());
        return nullptr;
    }
	m_fonts.emplace(std::move(key), std::unique_ptr<TTF_Font, SDLFontDeleter>(raw_Font));
	spdlog::info("加载字体成功: {} - {}", filePath, fontSize);
    return raw_Font;
}

TTF_Font* engine::resource::FontManager::getFont(const std::string& filePath, int fontSize)
{
    FontKey key = std::make_pair(filePath, fontSize);
	auto it = m_fonts.find(key);
    if (it != m_fonts.end())
    {
		return it->second.get();    
    }
    return loadFont(filePath, fontSize);
}

void engine::resource::FontManager::unloadFont(const std::string& filePath, int fontSize)
{
    FontKey key = std::make_pair(filePath, fontSize);
    auto it = m_fonts.find(key);
    if (it != m_fonts.end())
    {
        m_fonts.erase(it);
		spdlog::info("卸载字体成功: {} - {}", filePath, fontSize);
    }
    else
    {
		spdlog::warn("卸载字体失败: {} - {} - 字体未加载", filePath, fontSize);    
	}
}

void engine::resource::FontManager::clearFonts()
{
    if (!m_fonts.empty())
    {
        m_fonts.clear();
		spdlog::info("清除所有字体成功");
    }
}
